from flask import Blueprint, jsonify, request, current_app, g
import uuid
import time
from datetime import datetime

from applications.models.frontend import User, Address, Product, ProductCate, Cart, Order, OrderItem
from applications.extensions import db
from applications.view.miniapp.decorators import miniapp_login_required

# 创建小程序API蓝图
miniapp_api_bp = Blueprint('miniapp_api_bp', __name__, url_prefix='/miniapp/api')

# ====================== 用户模块 ======================

@miniapp_api_bp.route('/auth/login', methods=['POST'])
def login():
    """
    微信登录接口
    :return: 用户信息和token
    """
    try:
        data = request.json
        code = data.get('code')
        user_info = data.get('userInfo', {})
        
        if not code:
            return jsonify({'code': 400, 'message': '缺少微信code参数'}), 400
            
        # 微信登录凭证校验接口
        appid = current_app.config.get('WECHAT_APPID')
        secret = current_app.config.get('WECHAT_SECRET')
        
        # 模拟微信登录，实际项目中应该调用微信API
        # url = f'https://api.weixin.qq.com/sns/jscode2session?appid={appid}&secret={secret}&js_code={code}&grant_type=authorization_code'
        # response = requests.get(url)
        # result = response.json()
        
        # 模拟返回数据
        result = {
            'openid': f'openid_{int(time.time())}',
            'session_key': f'session_key_{uuid.uuid4().hex}',
            'unionid': f'unionid_{uuid.uuid4().hex}'
        }
        
        openid = result.get('openid')
        unionid = result.get('unionid')
        
        # 查找或创建用户
        user = User.query.filter_by(openid=openid).first()
        if not user:
            user = User(
                openid=openid,
                unionid=unionid,
                nickname=user_info.get('nickName', '微信用户'),
                avatar=user_info.get('avatarUrl', ''),
                gender=user_info.get('gender', 0),
                country=user_info.get('country', ''),
                province=user_info.get('province', ''),
                city=user_info.get('city', ''),
                enable=1  # 默认启用
            )
            db.session.add(user)
            db.session.commit()
            
        # 生成token
        token = generate_token(user.id, openid)
        
        return jsonify({
            'code': 200, 
            'message': '登录成功',
            'data': {
                'token': token,
                'user': {
                    'id': user.id,
                    'nickname': user.nickname,
                    'avatar_url': user.avatar,
                    'gender': user.gender,
                    'phone': user.phone,
                    'create_time': user.create_at.strftime('%Y-%m-%d %H:%M:%S') if user.create_at else None,
                }
            }
        })
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'登录失败: {str(e)}')
        return jsonify({'code': 500, 'message': f'登录失败: {str(e)}'}), 500

# 获取用户资料
@miniapp_api_bp.route('/user/profile', methods=['GET'])
@miniapp_login_required
def get_user_profile():
    """
    获取用户资料
    :return: 用户资料
    """
    try:
        user = g.user
        
        user_data = {
            'id': user.id,
            'nickname': user.nickname,
            'avatar_url': user.avatar,
            'gender': user.gender,
            'phone': user.phone,
            'country': user.country,
            'province': user.province,
            'city': user.city,
            'create_time': user.create_at.strftime('%Y-%m-%d %H:%M:%S') if user.create_at else None
        }
        
        return jsonify({'code': 200, 'message': '获取用户资料成功', 'data': user_data})
    except Exception as e:
        current_app.logger.error(f'获取用户资料失败: {str(e)}')
        return jsonify({'code': 500, 'message': f'获取用户资料失败: {str(e)}'}), 500

# 更新用户资料
@miniapp_api_bp.route('/user/profile', methods=['PUT'])
@miniapp_login_required
def update_user_profile():
    """
    更新用户资料
    :return: 更新结果
    """
    try:
        user = g.user
        data = request.json
        
        # 更新用户资料
        if 'nickname' in data:
            user.nickname = data['nickname']
        if 'avatar_url' in data:
            user.avatar = data['avatar_url']
        if 'gender' in data:
            user.gender = data['gender']
        if 'phone' in data:
            user.phone = data['phone']
            
        db.session.commit()
        
        return jsonify({'code': 200, 'message': '更新用户资料成功'})
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'更新用户资料失败: {str(e)}')
        return jsonify({'code': 500, 'message': f'更新用户资料失败: {str(e)}'}), 500

# 获取收货地址列表
@miniapp_api_bp.route('/user/address', methods=['GET'])
@miniapp_login_required
def get_addresses():
    """
    获取收货地址列表
    :return: 地址列表
    """
    try:
        user = g.user
        addresses = user.addresses
        
        address_list = [{
            'id': address.id,
            'receiver_name': address.recipient_name,
            'receiver_phone': address.phone,
            'address_line': address.address_line,
            'is_default': address.is_default
        } for address in addresses]
        
        return jsonify({'code': 200, 'message': '获取地址列表成功', 'data': address_list})
    except Exception as e:
        current_app.logger.error(f'获取地址列表失败: {str(e)}')
        return jsonify({'code': 500, 'message': f'获取地址列表失败: {str(e)}'}), 500

# 添加收货地址
@miniapp_api_bp.route('/user/address', methods=['POST'])
@miniapp_login_required
def add_address():
    """
    添加收货地址
    :return: 添加结果
    """
    try:
        user = g.user
        data = request.json
        
        # 验证必填字段
        required_fields = ['receiver_name', 'receiver_phone', 'address_line']
        for field in required_fields:
            if field not in data:
                return jsonify({'code': 400, 'message': f'缺少必填字段: {field}'}), 400
                
        # 创建新地址
        address = Address(
            user_id=user.id,
            recipient_name=data['receiver_name'],
            phone=data['receiver_phone'],
            address_line=data['address_line'],
            is_default=data.get('is_default', False)
        )
        
        # 如果设为默认地址，则将其他地址设为非默认
        if address.is_default:
            Address.query.filter_by(user_id=user.id, is_default=True).update({'is_default': False})
            
        db.session.add(address)
        db.session.commit()
        
        return jsonify({
            'code': 200, 
            'message': '添加地址成功',
            'data': {
                'id': address.id
            }
        })
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'添加地址失败: {str(e)}')
        return jsonify({'code': 500, 'message': f'添加地址失败: {str(e)}'}), 500

# 修改收货地址
@miniapp_api_bp.route('/user/address/<int:address_id>', methods=['PUT'])
@miniapp_login_required
def update_address(address_id):
    """
    修改收货地址
    :param address_id: 地址ID
    :return: 修改结果
    """
    try:
        user = g.user
        data = request.json
        
        # 查找地址并验证所有权
        address = Address.query.filter_by(id=address_id, user_id=user.id).first()
        if not address:
            return jsonify({'code': 404, 'message': '地址不存在或无权限修改'}), 404
            
        # 更新地址信息
        if 'receiver_name' in data:
            address.recipient_name = data['receiver_name']
        if 'receiver_phone' in data:
            address.phone = data['receiver_phone']
        if 'address_line' in data:
            address.address_line = data['address_line']
        if 'is_default' in data and data['is_default']:
            # 如果设为默认地址，则将其他地址设为非默认
            Address.query.filter_by(user_id=user.id, is_default=True).update({'is_default': False})
            address.is_default = True
            
        db.session.commit()
        
        return jsonify({'code': 200, 'message': '修改地址成功'})
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'修改地址失败: {str(e)}')
        return jsonify({'code': 500, 'message': f'修改地址失败: {str(e)}'}), 500

# 删除收货地址
@miniapp_api_bp.route('/user/address/<int:address_id>', methods=['DELETE'])
@miniapp_login_required
def delete_address(address_id):
    """
    删除收货地址
    :param address_id: 地址ID
    :return: 删除结果
    """
    try:
        user = g.user
        
        # 查找地址并验证所有权
        address = Address.query.filter_by(id=address_id, user_id=user.id).first()
        if not address:
            return jsonify({'code': 404, 'message': '地址不存在或无权限删除'}), 404
            
        # 删除地址
        db.session.delete(address)
        db.session.commit()
        
        return jsonify({'code': 200, 'message': '删除地址成功'})
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'删除地址失败: {str(e)}')
        return jsonify({'code': 500, 'message': f'删除地址失败: {str(e)}'}), 500

# 获取用户默认地址
@miniapp_api_bp.route('/user/address/default', methods=['GET'])
@miniapp_login_required
def get_default_address():
    """
    获取默认地址
    :return: 默认地址信息
    """
    try:
        user = g.user
        
        # 查找默认地址
        address = Address.query.filter_by(user_id=user.id, is_default=True).first()
        
        # 如果没有默认地址，则返回第一个地址
        if not address:
            address = Address.query.filter_by(user_id=user.id).first()
            
        if not address:
            return jsonify({'code': 200, 'message': '没有收货地址', 'data': None})
            
        address_data = {
            'id': address.id,
            'receiver_name': address.recipient_name,
            'receiver_phone': address.phone,
            'address_line': address.address_line,
            'is_default': address.is_default
        }
        
        return jsonify({'code': 200, 'message': '获取默认地址成功', 'data': address_data})
    except Exception as e:
        current_app.logger.error(f'获取默认地址失败: {str(e)}')
        return jsonify({'code': 500, 'message': f'获取默认地址失败: {str(e)}'}), 500


# ====================== 商品模块 ======================

@miniapp_api_bp.route('/product/<int:product_id>', methods=['GET'])
def get_product_detail(product_id):
    """
    获取商品详情
    :param product_id: 商品ID
    :return: 商品详情
    """
    try:
        product = Product.query.filter_by(id=product_id, status=1).first()
        if not product:
            return jsonify({'code': 404, 'message': '商品不存在或已下架'}), 404
            
        # 构建商品详情数据
        product_data = {
            'id': product.id,
            'name': product.name,
            'description': product.description,
            'price': product.price,
            'stock': product.stock,
            'sales': product.sales,
            'main_image': product.main_image,
            'images': product.image_list,
            'detail_html': product.detail_html,
            'category_id': product.category_id,
            'category_name': product.category.name if product.category else None,
            'brand': product.brand
        }
        
        return jsonify({'code': 200, 'message': '获取商品详情成功', 'data': product_data})
    except Exception as e:
        current_app.logger.error(f'获取商品详情失败: {str(e)}')
        return jsonify({'code': 500, 'message': f'获取商品详情失败: {str(e)}'}), 500


@miniapp_api_bp.route('/product/search', methods=['GET'])
def search_products():
    """
    商品搜索
    :return: 商品列表
    """
    try:
        # 获取查询参数
        page = int(request.args.get('page', 1))
        per_page = int(request.args.get('per_page', 10))
        keyword = request.args.get('keyword', '')
        category_id = request.args.get('category_id')
        min_price = request.args.get('min_price')
        max_price = request.args.get('max_price')
        sort_by = request.args.get('sort_by', 'create_time')
        sort_order = request.args.get('sort_order', 'desc')
        
        # 构建查询
        query = Product.query.filter_by(status=1)
        
        # 应用过滤条件
        if keyword:
            query = query.filter(Product.name.like(f'%{keyword}%'))
        if category_id:
            query = query.filter(Product.category_id == category_id)
        if min_price:
            query = query.filter(Product.price >= float(min_price))
        if max_price:
            query = query.filter(Product.price <= float(max_price))
            
        # 应用排序
        if sort_by == 'price':
            if sort_order == 'asc':
                query = query.order_by(Product.price.asc())
            else:
                query = query.order_by(Product.price.desc())
        elif sort_by == 'sales':
            query = query.order_by(Product.sales.desc())
        else:  # 默认按创建时间
            query = query.order_by(Product.create_time.desc())
            
        # 执行分页查询
        pagination = query.paginate(page=page, per_page=per_page)
        
        # 构建响应数据
        products = [{
            'id': product.id,
            'name': product.name,
            'price': product.price,
            'stock': product.stock,
            'sales': product.sales,
            'main_image': product.main_image,
            'category_id': product.category_id,
            'category_name': product.category.name if product.category else None
        } for product in pagination.items]
        
        return jsonify({
            'code': 200, 
            'message': '搜索商品成功',
            'data': {
                'products': products,
                'total': pagination.total,
                'pages': pagination.pages,
                'page': page,
                'per_page': per_page
            }
        })
    except Exception as e:
        current_app.logger.error(f'搜索商品失败: {str(e)}')
        return jsonify({'code': 500, 'message': f'搜索商品失败: {str(e)}'}), 500


@miniapp_api_bp.route('/category/list', methods=['GET'])
def get_category_list():
    """
    获取分类列表（树形结构）
    :return: 分类树
    """
    try:
        # 获取所有顶级分类
        categories = ProductCate.query.filter_by(parent_id=None, is_displayed=True).all()
        
        # 递归构建分类树
        def build_category_tree(category):
            children = category.children.filter_by(is_displayed=True).all()
            return {
                'id': category.id,
                'name': category.name,
                'imageUrl': category.image,
                'children': [build_category_tree(child) for child in children] if children else []
            }
        
        # 构建分类树数据
        category_tree = [build_category_tree(category) for category in categories]
        
        return jsonify({'code': 200, 'message': '获取分类列表成功', 'data': category_tree})
    except Exception as e:
        current_app.logger.error(f'获取分类列表失败: {str(e)}')
        return jsonify({'code': 500, 'message': f'获取分类列表失败: {str(e)}'}), 500


# 获取分类下的商品
@miniapp_api_bp.route('/category/<int:category_id>/products', methods=['GET'])
def get_category_products(category_id):
    """
    获取分类下的商品
    :param category_id: 分类ID
    :return: 商品列表
    """
    try:
        # 获取查询参数
        page = int(request.args.get('page', 1))
        per_page = int(request.args.get('limit', 10))
        
        # 验证分类是否存在
        category = ProductCate.query.get_or_404(category_id)
        
        # 查询该分类下的商品
        query = Product.query.filter_by(category_id=category_id, status=1)
        pagination = query.order_by(Product.create_time.desc()).paginate(page=page, per_page=per_page)
        
        # 构建响应数据
        products = [{
            'id': product.id,
            'name': product.name,
            'price': product.price,
            'stock': product.stock,
            'sales': product.sales,
            'main_image': product.main_image
        } for product in pagination.items]
        
        return jsonify({
            'code': 200, 
            'message': '获取分类商品成功',
            'data': {
                'category_name': category.name,
                'data': products,
                'total': pagination.total,
                'pages': pagination.pages,
                'page': page,
                'per_page': per_page
            }
        })
    except Exception as e:
        current_app.logger.error(f'获取分类商品失败: {str(e)}')
        return jsonify({'code': 500, 'message': f'获取分类商品失败: {str(e)}'}), 500


# ====================== 购物车模块 ======================

# 获取购物车商品
@miniapp_api_bp.route('/cart', methods=['GET'])
@miniapp_login_required
def get_cart_items():
    """
    获取购物车商品
    :return: 购物车商品列表
    """
    try:
        user_id = g.user_id
        cart_items = Cart.query.filter_by(user_id=user_id).all()
        
        items = []
        for item in cart_items:
            product = item.product
            if product and product.status == 1:
                items.append({
                    'id': item.id,
                    'product_id': item.product_id,
                    'product_name': product.name,
                    'product_image': product.main_image,
                    'price': product.price,
                    'quantity': item.quantity,
                    'stock': product.stock
                })
        
        return jsonify({'code': 200, 'message': '获取购物车成功', 'data': items})
    except Exception as e:
        current_app.logger.error(f'获取购物车失败: {str(e)}')
        return jsonify({'code': 500, 'message': f'获取购物车失败: {str(e)}'}), 500


# 添加商品到购物车
@miniapp_api_bp.route('/cart', methods=['POST'])
@miniapp_login_required
def add_to_cart():
    """
    添加商品到购物车
    :return: 添加结果
    """
    try:
        user_id = g.user_id
        data = request.json
        
        product_id = data.get('product_id')
        quantity = int(data.get('quantity', 1))
        
        if not product_id or quantity <= 0:
            return jsonify({'code': 400, 'message': '参数错误'}), 400
            
        # 验证商品是否存在
        product = Product.query.filter_by(id=product_id, status=1).first()
        if not product:
            return jsonify({'code': 404, 'message': '商品不存在或已下架'}), 404
            
        # 检查库存
        if product.stock < quantity:
            return jsonify({'code': 400, 'message': '商品库存不足'}), 400
            
        # 查找购物车中是否已有该商品
        cart_item = Cart.query.filter_by(user_id=user_id, product_id=product_id).first()
        
        if cart_item:
            # 更新数量
            cart_item.quantity += quantity
            if cart_item.quantity > product.stock:
                cart_item.quantity = product.stock
        else:
            # 添加新商品到购物车
            cart_item = Cart(
                user_id=user_id,
                product_id=product_id,
                quantity=quantity
            )
            db.session.add(cart_item)
            
        db.session.commit()
        
        return jsonify({'code': 200, 'message': '添加到购物车成功'})
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'添加到购物车失败: {str(e)}')
        return jsonify({'code': 500, 'message': f'添加到购物车失败: {str(e)}'}), 500


# 修改购物车商品
@miniapp_api_bp.route('/cart/<int:cart_item_id>', methods=['PUT'])
@miniapp_login_required
def update_cart_item(cart_item_id):
    """
    更新购物车商品
    :param cart_item_id: 购物车项ID
    :return: 更新结果
    """
    try:
        user_id = g.user_id
        data = request.json
        
        # 查找购物车项并验证所有权
        cart_item = Cart.query.filter_by(id=cart_item_id, user_id=user_id).first()
        if not cart_item:
            return jsonify({'code': 404, 'message': '购物车商品不存在'}), 404
            
        # 更新数量
        if 'quantity' in data:
            quantity = int(data['quantity'])
            if quantity <= 0:
                # 数量为0则删除
                db.session.delete(cart_item)
            else:
                # 检查库存
                product = Product.query.get(cart_item.product_id)
                if not product or product.status != 1:
                    return jsonify({'code': 400, 'message': '商品不存在或已下架'}), 400
                    
                if quantity > product.stock:
                    quantity = product.stock
                    
                cart_item.quantity = quantity
                
        db.session.commit()
        
        return jsonify({'code': 200, 'message': '更新购物车成功'})
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'更新购物车失败: {str(e)}')
        return jsonify({'code': 500, 'message': f'更新购物车失败: {str(e)}'}), 500

# 删除购物车商品
@miniapp_api_bp.route('/cart/<int:cart_item_id>', methods=['DELETE'])
@miniapp_login_required
def delete_cart_item(cart_item_id):
    """
    删除购物车商品
    :param cart_item_id: 购物车项ID
    :return: 删除结果
    """
    try:
        user_id = g.user_id
        # 查找购物车项并验证所有权
        cart_item = Cart.query.filter_by(id=cart_item_id, user_id=user_id).first()
        if not cart_item:
            return jsonify({'code': 404, 'message': '购物车商品不存在'}), 404
            
        # 删除购物车项
        db.session.delete(cart_item)
        db.session.commit()
        
        return jsonify({'code': 200, 'message': '删除购物车商品成功'})
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'删除购物车商品失败: {str(e)}')
        return jsonify({'code': 500, 'message': f'删除购物车商品失败: {str(e)}'}), 500

# 清空购物车
@miniapp_api_bp.route('/cart/clear', methods=['DELETE'])
@miniapp_login_required
def clear_cart():
    """
    清空购物车
    :return: 清空结果
    """
    try:
        user_id = g.user_id
        Cart.query.filter_by(user_id=user_id).delete()
        db.session.commit()
        return jsonify({'code': 200, 'message': '清空购物车成功'})
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'清空购物车失败: {str(e)}')
        return jsonify({'code': 500, 'message': f'清空购物车失败: {str(e)}'}), 500


# ====================== 订单模块 ======================
# 创建订单
@miniapp_api_bp.route('/orders', methods=['POST'])
@miniapp_login_required
def create_order():
    """
    创建订单
    :return: 订单信息
    """
    try:
        user = g.user
        data = request.json
        
        # 获取地址ID
        address_id = data.get('address_id')
        if not address_id:
            return jsonify({'code': 400, 'message': '请选择收货地址'}), 400
            
        # 验证地址是否存在
        address = Address.query.filter_by(id=address_id, user_id=user.id).first()
        if not address:
            return jsonify({'code': 404, 'message': '收货地址不存在'}), 404
            
        # 获取购物车选中的商品
        cart_items = Cart.query.filter_by(user_id=user.id).all() # 假设全选
        if not cart_items:
            return jsonify({'code': 400, 'message': '请选择要购买的商品'}), 400
            
        # 计算订单金额
        total_amount = 0
        order_items_data = []
        
        for cart_item in cart_items:
            product = Product.query.get(cart_item.product_id)
            if not product or product.status != 1:
                return jsonify({'code': 400, 'message': f'商品 {product.name if product else "未知商品"} 不存在或已下架'}), 400
                
            if product.stock < cart_item.quantity:
                return jsonify({'code': 400, 'message': f'商品 {product.name} 库存不足'}), 400
                
            # 计算商品总价
            item_amount = product.price * cart_item.quantity
            total_amount += item_amount
            
            # 创建订单项
            order_items_data.append({
                'product_id': product.id,
                'quantity': cart_item.quantity,
                'price': product.price,
            })
            
        # 生成订单号
        order_no = f'ORDER{int(time.time())}{user.id}'
        
        # 创建订单
        order = Order(
            order_no=order_no,
            user_id=user.id,
            total_amount=total_amount,
            status=0,  # 待支付
            recipient_name=address.recipient_name,
            phone=address.phone,
            address=address.address_line
        )
        
        db.session.add(order)
        db.session.flush()  # 获取订单ID
        
        # 创建订单商品
        for item_data in order_items_data:
            order_item = OrderItem(
                order_id=order.id,
                product_id=item_data['product_id'],
                quantity=item_data['quantity'],
                price=item_data['price']
            )
            db.session.add(order_item)
            
            # 减少库存，增加销量
            product = Product.query.get(item_data['product_id'])
            product.stock -= item_data['quantity']
            product.sales += item_data['quantity']
            
        # 清空购物车中已购买的商品
        for cart_item in cart_items:
            db.session.delete(cart_item)
            
        db.session.commit()
        
        return jsonify({
            'code': 200, 
            'message': '创建订单成功',
            'data': {
                'order_id': order.id,
                'order_no': order.order_no,
                'pay_amount': order.total_amount
            }
        })
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'创建订单失败: {str(e)}')
        return jsonify({'code': 500, 'message': f'创建订单失败: {str(e)}'}), 500


@miniapp_api_bp.route('/orders', methods=['GET'])
@miniapp_login_required
def get_user_orders():
    """
    获取用户订单列表
    :return: 订单列表
    """
    try:
        user = g.user
        
        # 获取查询参数
        page = int(request.args.get('page', 1))
        per_page = int(request.args.get('per_page', 10))
        status = request.args.get('status')
        
        # 构建查询
        query = Order.query.filter_by(user_id=user.id)
        
        # 按状态筛选
        if status is not None:
            query = query.filter_by(status=int(status))
            
        # 执行分页查询
        pagination = query.order_by(Order.create_at.desc()).paginate(page=page, per_page=per_page)
        
        # 构建响应数据
        orders = []
        for order in pagination.items:
            # 获取订单商品
            items = []
            for item in order.order_items:
                product = item.product
                if product:
                    items.append({
                        'id': item.id,
                        'product_id': item.product_id,
                        'product_name': product.name,
                        'product_image': product.main_image,
                        'quantity': item.quantity,
                        'price': item.price
                    })
            
            # 构建订单数据
            orders.append({
                'id': order.id,
                'order_no': order.order_no,
                'total_amount': order.total_amount,
                'status': order.status,
                'status_text': get_order_status_text(order.status),
                'create_time': order.create_at.strftime('%Y-%m-%d %H:%M:%S') if order.create_at else None,
                'items': items
            })
        
        return jsonify({
            'code': 200, 
            'message': '获取订单列表成功',
            'data': {
                'orders': orders,
                'total': pagination.total,
                'pages': pagination.pages,
                'page': page,
                'per_page': per_page
            }
        })
    except Exception as e:
        current_app.logger.error(f'获取订单列表失败: {str(e)}')
        return jsonify({'code': 500, 'message': f'获取订单列表失败: {str(e)}'}), 500


@miniapp_api_bp.route('/orders/<int:order_id>', methods=['GET'])
@miniapp_login_required
def get_order_detail(order_id):
    """
    获取订单详情
    :param order_id: 订单ID
    :return: 订单详情
    """
    try:
        user = g.user
        
        # 查找订单并验证所有权
        order = Order.query.filter_by(id=order_id, user_id=user.id).first()
        if not order:
            return jsonify({'code': 404, 'message': '订单不存在'}), 404
            
        # 获取订单商品
        items = []
        for item in order.order_items:
            product = item.product
            if product:
                items.append({
                    'id': item.id,
                    'product_id': item.product_id,
                    'product_name': product.name,
                    'product_image': product.main_image,
                    'quantity': item.quantity,
                    'price': item.price
                })
        
        # 获取收货地址
        address_data = {
            'receiver_name': order.recipient_name,
            'receiver_phone': order.phone,
            'address_line': order.address
        }
        
        # 构建订单详情数据
        order_data = {
            'id': order.id,
            'order_no': order.order_no,
            'total_amount': order.total_amount,
            'status': order.status,
            'status_text': get_order_status_text(order.status),
            'remark': order.remark,
            'create_time': order.create_at.strftime('%Y-%m-%d %H:%M:%S') if order.create_at else None,
            'payment_time': order.payment_time.strftime('%Y-%m-%d %H:%M:%S') if order.payment_time else None,
            'address': address_data,
            'items': items
        }
        
        return jsonify({'code': 200, 'message': '获取订单详情成功', 'data': order_data})
    except Exception as e:
        current_app.logger.error(f'获取订单详情失败: {str(e)}')
        return jsonify({'code': 500, 'message': f'获取订单详情失败: {str(e)}'}), 500


@miniapp_api_bp.route('/orders/<int:order_id>/cancel', methods=['POST'])
@miniapp_login_required
def cancel_order(order_id):
    """
    取消订单
    :param order_id: 订单ID
    :return: 取消结果
    """
    try:
        user = g.user
        
        # 查找订单并验证所有权
        order = Order.query.filter_by(id=order_id, user_id=user.id).first()
        if not order:
            return jsonify({'code': 404, 'message': '订单不存在'}), 404
            
        # 只有待支付状态的订单可以取消
        if order.status != 0:
            return jsonify({'code': 400, 'message': '只有待支付的订单可以取消'}), 400
            
        # 更新订单状态
        order.status = 4  # 已取消
        
        # 恢复库存
        for item in order.order_items:
            product = Product.query.get(item.product_id)
            if product:
                product.stock += item.quantity
                product.sales -= item.quantity
                
        db.session.commit()
        
        return jsonify({'code': 200, 'message': '取消订单成功'})
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'取消订单失败: {str(e)}')
        return jsonify({'code': 500, 'message': f'取消订单失败: {str(e)}'}), 500


@miniapp_api_bp.route('/orders/<int:order_id>/pay', methods=['POST'])
@miniapp_login_required
def pay_order(order_id):
    """
    支付订单（模拟）
    :param order_id: 订单ID
    :return: 支付结果
    """
    try:
        user = g.user
        
        # 查找订单并验证所有权
        order = Order.query.filter_by(id=order_id, user_id=user.id).first()
        if not order:
            return jsonify({'code': 404, 'message': '订单不存在'}), 404
            
        # 只有待支付状态的订单可以支付
        if order.status != 0:
            return jsonify({'code': 400, 'message': '订单状态错误，无法支付'}), 400
            
        # 更新订单状态（模拟支付成功）
        order.status = 1  # 已支付
        order.payment_time = datetime.now()
        
        db.session.commit()
        
        return jsonify({'code': 200, 'message': '支付成功'})
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'支付订单失败: {str(e)}')
        return jsonify({'code': 500, 'message': f'支付订单失败: {str(e)}'}), 500


@miniapp_api_bp.route('/orders/<int:order_id>/confirm', methods=['POST'])
@miniapp_login_required
def confirm_order(order_id):
    """
    确认收货
    :param order_id: 订单ID
    :return: 确认结果
    """
    try:
        user = g.user
        
        # 查找订单并验证所有权
        order = Order.query.filter_by(id=order_id, user_id=user.id).first()
        if not order:
            return jsonify({'code': 404, 'message': '订单不存在'}), 404
            
        # 只有已发货状态的订单可以确认收货
        if order.status != 2:
            return jsonify({'code': 400, 'message': '只有已发货的订单可以确认收货'}), 400
            
        # 更新订单状态
        order.status = 3  # 已完成
        
        db.session.commit()
        
        return jsonify({'code': 200, 'message': '确认收货成功'})
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'确认收货失败: {str(e)}')
        return jsonify({'code': 500, 'message': f'确认收货失败: {str(e)}'}), 500


# ====================== 辅助函数 ======================

def generate_token(user_id, openid):
    """
    生成JWT token
    :param user_id: 用户ID
    :param openid: 微信openid
    :return: token字符串
    """
    # 实际项目中应该使用JWT库生成token
    # 这里简单模拟
    return f'token_{user_id}_{openid}_{int(time.time())}'


def get_order_status_text(status):
    """
    获取订单状态文本
    :param status: 状态码
    :return: 状态文本
    """
    status_map = {
        0: '待支付',
        1: '已支付',
        2: '已发货',
        3: '已完成',
        4: '已取消',
        5: '已退款'
    }
    return status_map.get(status, '未知状态')


def register_miniapp_api_bps(app):
    """
    注册小程序API蓝图
    :param app: Flask应用实例
    :return: None
    """
    app.register_blueprint(miniapp_api_bp)
